﻿using System;
using System.IO;

namespace Iorz.DomainSearch.Utils.Tools
{
    /// <summary>
    /// 记录日志文本
    /// </summary>
    public class Tracker
    {
        private const string directory = "Log";

        public static void e(Exception ex)
        {
            string message = string.Format("Message={0} StackTrace={1}", ex.Message, ex.StackTrace);
            Write("error.log", message);
        }

        public static void e(string message, params object[] parameters)
        {
            message = string.Format(message, parameters);
            e(message);
        }

        public static void e(string message)
        {
            Write("error.log", message);
        }

        public static void i(string message, params object[] parameters)
        {
            message = string.Format(message, parameters);
            i(message);
        }

        public static void i(string message)
        {
            Write("info.log", message);
        }

        public static void Log(string filename, string message, params object[] parameters)
        {
            message = string.Format(message, parameters);
            Log(filename, message);
        }

        public static void Log(string filename, string message)
        {
            filename = string.IsNullOrEmpty(filename) ? "info.log" : filename;
            Write(filename, message);
        }

        private static void Write(string filename, string message)
        {
            try
            {
                string file = GetLogFileName(filename);
                message = GetMessage(message);
                using (FileStream fs = new FileStream(file, File.Exists(file) ? FileMode.Append : FileMode.Create, FileAccess.Write))
                {
                    StreamWriter log = new StreamWriter(fs, System.Text.Encoding.Default);
                    log.WriteLine(message);
                    log.Close();
                }

                Console.WriteLine(message);
            }
            catch
            {
            }
        }

        private static string GetMessage(string message)
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "：" + message;
        }

        private static string GetLogFileName(string filename)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + directory;
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            return path + "\\" + filename;
        }
    }
}
